package com.ec.cr.controller;


import com.ec.api.domain.po.MedicineRecord;
import com.ec.cr.domain.vo.MedicineRecordVO;
import com.ec.cr.domain.vo.StatItemVO;
import com.ec.cr.service.MedicineRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/medicine/record")
//@CrossOrigin // 如果是前后端分离，允许跨域请求
public class MedicineRecordController {

    @Autowired
    private MedicineRecordService medicineRecordService;

    /** 分页查询：改为按 elderlyUserId 和 drugName 过滤 */
    @GetMapping("/list")
    public Map<String, Object> getPagedRecords(
            @RequestParam(defaultValue = "1")     int    page,
            @RequestParam(defaultValue = "10")    int    pageSize,
            @RequestParam                         Long   elderlyUserId,
            @RequestParam(required = false)      String drugName) {

        // 1. 总数
        long total = medicineRecordService.countRecordsByUserId(elderlyUserId, drugName);
        // 2. 分页数据
        List<MedicineRecordVO> records =
                medicineRecordService.findPageRecordsByUserId(elderlyUserId, drugName, page, pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("data",  records);
        result.put("total", total);
        return result;
    }



    @GetMapping("/elderly-list")
    public List<Map<String, Object>> getElderlyList() {
        System.out.println("=== 接收到GET请求 /api/medicine/record/elderly-list ===");

        List<Map<String, Object>> result = medicineRecordService.getElderlySimpleList();
        System.out.println("老人数量: " + result.size());
        return result;
    }


    // 添加记录
    @PostMapping("/add")
    public String addRecord(@RequestBody MedicineRecord record) {
        medicineRecordService.addRecord(record);
        return "添加成功";
    }

    // 更新记录
    @PutMapping("/update")
    public String updateRecord(@RequestBody MedicineRecord record) {
        medicineRecordService.updateRecord(record);
        return "更新成功";
    }

    // 删除记录
    @DeleteMapping("/delete/{id}")
    public String deleteRecord(@PathVariable Integer id) {
        medicineRecordService.deleteRecord(id);
        return "删除成功";
    }


    /**
     * 用药统计接口
     * @param elderlyUserId 老人 ID
     * @return 包含 line（按月）、pie（按药品）、bar（按日）三组数据
     */
    @GetMapping("/stats")
    public Map<String, List<StatItemVO>> stats(@RequestParam Long elderlyUserId) {
        List<StatItemVO> line = medicineRecordService.countByMonth(elderlyUserId);
        List<StatItemVO> pie  = medicineRecordService.sumByDrug(elderlyUserId);
        List<StatItemVO> bar  = medicineRecordService.sumCostByDay(elderlyUserId);

        Map<String, List<StatItemVO>> result = new HashMap<>();
        result.put("line", line);
        result.put("pie",  pie);
        result.put("bar",  bar);
        return result;
    }



}

